﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WordsOfLoveServer.Models;
using WordsOfLoveServer.Models.Forums;

namespace WordsOfLoveServer.Controllers
{
    public class WordInfoController : ApiController
    {
		//GET: api/WordInfo/GetWordInfo?word=xxx
		[HttpGet]
		public HttpResponseMessage GetWordInfo(string word)
		{
			try
			{
				using(WOLDbContext db = new WOLDbContext())
				{
					IQueryable<ForumPost> relatedPosts =
						from post in db.ForumPosts
						join tag in db.ForumPostTags
						on post.Id equals tag.PostId
						where tag.Content == word
						select post;
					IQueryable<ForumPost> hotPosts =
						from post in relatedPosts
						join like in db.ForumPostLikes
						on post.Id equals like.PostId into plg
						from plgi in plg.DefaultIfEmpty()
						group plgi by post into g
						orderby g.Count() descending
						select g.Key;

					IQueryable<Sentence> relatedSentences =
						from sentence in db.Sentences
						where sentence.Word == word
						select sentence;
					IQueryable<Sentence> hotSentences =
						from sentence in relatedSentences
						join like in db.ForumPostLikes
						on sentence.Id equals like.PostId into slg
						from slgi in slg.DefaultIfEmpty()
						group slgi by sentence into g
						orderby g.Count() descending
						select g.Key;

					WordInfo info = new WordInfo()
					{
						HotPosts = hotPosts.Take(3).ToList(),
						HotSentences = hotSentences.Take(3).ToList()
					};
					return new HttpResponseMessage()
					{
						RequestMessage = Request,
						Content = new StringContent(JsonConvert.SerializeObject(info))
				};
				}
			}
			catch (Exception ex)
			{
				return new HttpResponseMessage(HttpStatusCode.BadRequest)
				{
					Content = new StringContent(ex.Message)
				};
			}
		}
    }
}
